package com.meisiabc.app.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meisiabc.app.repository.db.entity.*;
import com.meisiabc.app.repository.db.manager.*;
import com.meisiabc.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/***
 * @Author: jiyang
 * @Date: 2018-12-20 15:24
 */
@Slf4j
@Service
public class SmsPushService {

    @Autowired
    private CurriculumScheduleManager curriculumScheduleManager;

    @Autowired
    private StudentManager studentManager;

    @Autowired
    private WechatMpSessionManager wechatMpSessionManager;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private LessonManager lessonManager;

    @Autowired
    private TrylistenmanageManager trylistenmanageManager;

    @Autowired
    private LeaveRequestManager leaveRequestManager;

    @Autowired
    private TeacherManager teacherManager;


    public void classReminderPush() {
        String begin = DateUtil.addDayStr(new Date(), -2);
        String end = DateUtil.addDayStr(new Date(), 3);
        log.info("date begin:" + begin + " end:" + end);

        List<CurriculumSchedule> curriculumSchedules = curriculumScheduleManager.selectUnFinashedClasses(begin, end);

        log.info("curriculumSchedules is: {}", JSON.toJSONString(curriculumSchedules));

        for (CurriculumSchedule schedule : curriculumSchedules) {
            try {
                log.info("schedule is :" + JSON.toJSONString(schedule));
                if (schedule.getState() != null && (schedule.getState() == 2 || schedule.getState() == 4)) { //学生、外教请假
                    continue;
                }else {
                    log.info("schedule.getState():" + schedule.getState());
                }

                StringBuilder courseName = new StringBuilder();
                if (schedule.getTeacherId() != null) {
                    Teacher teacher = teacherManager.selectByUniqueid(schedule.getTeacherId());
                    if (teacher != null && StringUtils.isNotBlank(teacher.getName())) {
                        courseName.append(teacher.getName() + " ");
                    }
                }

                String classDate = DateUtil.defalultFomrt(schedule.getClassDate()) + " " + schedule.getClassTime().split(":")[0];
                String now = DateUtil.defalultFomrt(new Date(), "yyyy-MM-dd HH");


                int hoursDiff = DateUtil.hoursDiff(now, classDate);

                log.info("classbegin:{},now:{},diff:{},studentId:{},classId:{}", classDate, now, hoursDiff,schedule.getStudentId(),schedule.getId());
                if (hoursDiff == 8 || hoursDiff == 1) {
                    Student student = studentManager.selectByUnId(schedule.getStudentId());
                    Lesson lesson = lessonManager.selectById(schedule.getMaterial());

                    String classBeginTime = DateUtil.defalultFomrt(schedule.getClassDate(), "yyyy-MM-dd") + " " + schedule.getClassTime() + "-" + schedule.getClassTimeEnd();

                    if (student != null && StringUtils.isNotBlank(student.getPhone()) && lesson != null) {

                        WechatMpSession wechatMpSession = wechatMpSessionManager.getOne(new QueryWrapper<WechatMpSession>().eq("mobile", student.getPhone()));
                        if (wechatMpSession != null && StringUtils.isNotBlank(wechatMpSession.getOpenid())) {
                            log.info("上课提醒phone:{},studentId:{},classId:{}", student.getPhone(), student.getStudentId(), schedule.getId());
                            wechatService.smsClassBegin(wechatMpSession.getOpenid(), student.getEnName(), courseName.append(lesson.getNameZh()).toString(), classBeginTime);
                        } else {
                            log.error("定时任务上课前提醒异常，WechatMpSession不存在");
                        }
                    }
                }
            } catch (Exception e) {
                log.error("上课提醒异常", e);
            }
        }
        classReminderPushFree();
    }

    private void classReminderPushFree() {
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<Trylistenmanage> Trylistenmanages = trylistenmanageManager.selectList(now);
        for (Trylistenmanage trylistenmanage : Trylistenmanages) {
            try {
                StringBuilder courseName = new StringBuilder();
                if (trylistenmanage != null && StringUtils.isNotBlank(trylistenmanage.getTeacherId())) {
                    Teacher teacher = teacherManager.selectByUniqueid(trylistenmanage.getTeacherId());
                    if (teacher != null && StringUtils.isNotBlank(teacher.getName())) {
                        courseName.append(teacher.getName() + " ");
                    }
                }

                //2019-01-09 , Wednesday 21:00-21:15 21:15-21:30
                String date = trylistenmanage.getAuditionTime().split(",")[0].trim();
                String time = trylistenmanage.getAuditionTime().split(",")[1].trim().split(" ")[1].trim().split("-")[0].trim().split(":")[0].trim();

                String nowDate = DateUtil.defalultFomrt(new Date(), "yyyy-MM-dd HH");

                int hoursDiff = DateUtil.hoursDiff(nowDate, date + " " + time);
                log.info("classbegin:{},now:{},diff:{}", trylistenmanage.getAuditionTime(), nowDate, hoursDiff);
                if (hoursDiff == 8 || hoursDiff == 1) {

                    String timeBegin = date + " " + trylistenmanage.getAuditionTime().split(",")[1].trim().split(" ")[1].trim().split("-")[0].trim() +
                            "-" + trylistenmanage.getAuditionTime().split(",")[1].trim().split(" ")[2].trim().split("-")[1].trim();

                    Student student = studentManager.selectByUnId(trylistenmanage.getStudentId());
                    Lesson lesson = lessonManager.selectById(trylistenmanage.getMaterial());

                    if (student != null && StringUtils.isNotBlank(student.getPhone()) && lesson != null) {
                        WechatMpSession wechatMpSession = wechatMpSessionManager.getOne(new QueryWrapper<WechatMpSession>().eq("mobile", student.getPhone()));
                        if (wechatMpSession != null && StringUtils.isNotBlank(wechatMpSession.getOpenid())) {
                            log.info("上课提醒phone:{},studentId:{},classId:{}", student.getPhone(), student.getStudentId(), trylistenmanage.getId());
                            wechatService.smsClassBegin(wechatMpSession.getOpenid(), student.getEnName(), courseName.append(lesson.getNameZh()).toString(), timeBegin);
                        } else {
                            log.error("定时任务上课前提醒异常，WechatMpSession不存在");
                        }
                    }
                }
            } catch (Exception e){
                log.error("免费试听提醒",e);
            }
        }
    }

    public void teacherLeaveSendNotice() {
        List<LeaveRequest> noSendSms = leaveRequestManager.getNoSendSms();
        for (LeaveRequest request : noSendSms) {
            Student student = studentManager.selectByUnId(request.getStudentId());
            if (student != null && StringUtils.isNotBlank(student.getPhone())) {
                WechatMpSession wechatMpSession = wechatMpSessionManager.getOne(new QueryWrapper<WechatMpSession>().eq("mobile", student.getPhone()));

                if (wechatMpSession != null && StringUtils.isNotBlank(wechatMpSession.getOpenid())) {

                    LocalDateTime localDateTime = LocalDateTime.ofInstant(request.getClassDate().toInstant(),  ZoneId.systemDefault());
                    String classTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " " + request.getClassPeriod();
                    wechatService.smsTeacherLeave(wechatMpSession.getOpenid(), request.getStudentName(), request.getTeacherName(), request.getClassName(), classTime);
                } else {
                    log.error("定时任务上课前提醒异常，WechatMpSession不存在");
                }
            }
            request.setSendSms(1);
            leaveRequestManager.updateById(request);
        }
    }
}
